import Vue from "vue"; // 导入vue
import Main from "./index.vue"; // 导入组件

// 将组件作为参数，使用vue提供的全局方法，创建一个构造函数
let DrawerConstructor = Vue.extend(Main);

let instance;

const Drawer = function ({
    title = "",
    type,
    selection = false,
    params = {},
    toastSureBtn = "确定",
    toastFailBtn = "取消",
}) {
    return new Promise((resolve, reject) => {
        // 初始化实例，此时instance是一个组件实例，但未初始化未完成
        instance = new DrawerConstructor({
            data: {
                title,
                type,
                params,
                selection,
                toastSureBtn,
                toastFailBtn,
            },
            methods: {
                Select: (res,type) => {
                    unmount();
                    resolve({res,type});
                },
                Cancel: (err = "close") => {
                    unmount();
                    reject(err);
                },
            },
        });
        // 卸载组件
        const unmount = () => {
            instance.visible = false;
        };
        // 完成初始化
        instance.$mount();

        // 将组件添加到根节点body
        document.body.appendChild(instance.$el);
        instance.visible = true;
    });
};

export default Drawer;
